package com.radio.view;

import java.text.SimpleDateFormat;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;

public class EventRadio extends View implements AdapterView.OnItemClickListener, AdapterView.OnItemSelectedListener, View.OnClickListener {
	
	private static final String TAG = "RadioProgram";
	private boolean flag = false;
	private int time = 0;
	RadioProgram rp;
	SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
	
	public EventRadio(Context context, RadioProgram rp){
		super(context);
		this.rp = rp;
	}
	
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.idplaybutton:
			if (time == 0){
				doTime();
			}else{
				mHandler.removeMessages(0);
				flag = false;
			}
			rp.getmIBpause().setVisibility(View.VISIBLE);
			rp.getmIBplay().setVisibility(View.GONE);
			break;
		case R.id.idpausebutton:
			doTime();
			rp.getmIBplay().setVisibility(View.VISIBLE);
			rp.getmIBpause().setVisibility(View.GONE);
			break;
		case R.id.idstopbutton:
			rp.getmTVTime().setText("00:00");
			time = 0;
			mHandler.removeMessages(0);
			flag = false;
			
			if(rp.getmIBplay().isEnabled() == true){
				rp.getmIBplay().setVisibility(View.VISIBLE);
				rp.getmIBpause().setVisibility(View.GONE);
			}
			
			break;
		default:
			break;
		}
	}

	public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {
		Log.d(TAG, "onItemClick : " + arg2);
		rp.getmTVFrequency().setText(rp.getMfrequency()[arg2]);
		time = 0;
		doTime();
		
		if(rp.getmIBplay().isEnabled() == true){
			rp.getmIBplay().setVisibility(View.VISIBLE);
			rp.getmIBpause().setVisibility(View.GONE);
		}
	}
	
	public void onItemSelected(AdapterView<?> arg0, View v, int arg2, long arg3) {
		Log.d(TAG, "onItemClick : " + arg2);
		rp.getmTVFrequency().setText("" + rp.getmLV().getSelectedItem());
		time = 0;
		doTime();
		
		if(rp.getmIBplay().isEnabled() == true){
			rp.getmIBplay().setVisibility(View.VISIBLE);
			rp.getmIBpause().setVisibility(View.GONE);
		}
	}

	public void onNothingSelected(AdapterView<?> arg0) {
//		TODO Nothing 
		}
	
	public void doTime() {
		if (flag == false) {
			mHandler.sendEmptyMessage(0);
			flag = true;
		}
    }

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			rp.getmTVTime().setText(DateUtils.formatElapsedTime(time));
			time++;
			mHandler.sendEmptyMessageDelayed(0, 1000);
		}
	};
}